<script>
import { ToastFun } from "@/hook/toast";
import { DateFun } from "@/utils/dateFun";
import { useUseStore } from "@/stores/user";
import { getChatRecord, saveChatRecord } from "@/server/api/chatApi";

import { messageStore } from "@/stores/message";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
let newMsgList = [];
// 在网页关闭时调用接口
window.addEventListener("beforeunload", () => {
  if (newMsgList.length != 0) {
    console.log(newMsgList);
    saveChatRecord(newMsgList);
  }
});
console.log(useUseStore().userInfo);
export default {
  data() {
    let msg = ""; // 发送的消息对象
    let msgList = []; // 消息列表
    let showPlus = false; // 显示更多
    let userId = useUseStore().userId; // 用户Id
    let newMsgList = []; // 新增聊天记录，用户发送到后端
    //我作为卖家时我的店铺id
    let shopId = useUseStore().itemId;
    let itemName = messageStore().itemObj.itemName; // 店铺名字
    let itemImg = messageStore().itemObj.itemImg; // 店铺图片

    let commodityInfo = messageStore().itemObj.commodityInfo || null;

    // 获取聊天记录的请求体
    let getChatReq = {
      senderId: userId,
      receiverId: messageStore().itemObj.itemId,
      page: 1,
      limit: 10,
    };
    //右侧聊天的头像
    let receiverImg = useUseStore().userInfo.userImage || '/images/Message/avatar1.png';

    return {
      msg,
      msgList,
      showPlus,
      userId,
      getChatReq,
      newMsgList,
      itemImg,
      itemName,
      commodityInfo,
      receiverImg,
      shopId
    };
  },

  methods: {
    input() {
      let msg = {
        receiverId: messageStore().itemObj.itemId,
        message: this.msg,
        sendTime: DateFun({ timestamp: new Date().getTime() }),
        senderId: this.userId,
      };

      // 正则判断输入内容是否为空
      let rex = /\S+/;
      if (rex.test(this.msg)) {
        //
        this.msgList.list.push(msg);

        // 用于发送到后端的新数组
        this.newMsgList.push(msg);
        newMsgList.push(msg);
        console.log(this.newMsgList);

        this.$socket.emit("Chat", msg);
      } else {
        // 轻提示
        ToastFun("show", {
          msg: t("shopSeller.emptyContent"),
          position: "bottom",
        });
      }

      this.msg = "";
    },

    // 获取聊天记录接口
    getChatRecordFun() {
      getChatRecord(this.getChatReq).then(({ data }) => {
        console.log(this.getChatReq, "是什么");
        console.log(data.data);
        this.msgList = data.data;
      });
    },

    // 保存聊天记录接口
    saveChatRecordFun() {
      if (this.newMsgList.length != 0) {
        console.log(this.newMsgList);
        saveChatRecord(this.newMsgList).then(({ data }) => {
          console.log(data.data);
        });
      }
    },
  },
  // 监听点了"买家"还是"卖家"
  // watch: {
  //   'messageStore().sellerOrbuyer': {
  //     immediate: true,
  //     handler() {
  //       console.log(messageStore().sellerOrbuyer, "0买家，1卖家");
  //     }
  //   }
  // },
  beforeMount() {
    if (messageStore().sellerOrbuyer == 0) {
      this.getChatReq.senderId = useUseStore().itemId;
    } else {
      this.getChatReq.senderId = useUseStore().userId;
    }
    this.getChatRecordFun(); // 获取聊天记录接口
    console.log(messageStore().itemObj);
  },

  beforeUnmount() {
    this.saveChatRecordFun();
  },

  sockets: {
    privateChatMessage(msg) {
      console.log(msg);
      this.msgList.push(msg);
    },
  },
};
</script>

<template>
  <div>
    <div class="outside">
      <!-- 头部一栏 -->
      <div class="header">
        <div class="back" @click="$router.back()">
          <img src="/images/Message/back.png" alt="" />
        </div>
        <div class="personName">{{ itemName }}</div>
      </div>

      <div class="loadingView" v-if="!msgList.list">
        <van-skeleton title :row="3" />
        <van-skeleton title avatar :row="3" />
        <van-skeleton title avatar :row="3" />
        <van-skeleton title avatar :row="3" />
        <van-skeleton title avatar :row="3" />
      </div>

      <div class="album" v-if="msgList.list && commodityInfo">
        <div class="albumPic">
          <img v-lazy="commodityInfo.commodityImg" alt="" />
        </div>
        <div class="albumInfo">{{ commodityInfo.commodityName }}</div>
        <div class="price"><span>eCNY</span> {{ commodityInfo.price }}</div>
      </div>

      <!-- 聊天 -->
      <div class="communication" v-if="msgList.list">
        <div :class="['item', item.senderId === userId || item.senderId === shopId ? 'sender' : '']"
          v-for="(item, index) in msgList.list" :key="index">
          <div class="userAvatar">
            <img :src="item.senderId === userId || item.senderId === shopId
              ? receiverImg
              : itemImg || `/images/Message/avatar1.png`
              " alt="" />
          </div>

          <div class="message">{{ item.message }}</div>
        </div>
      </div>

      <!-- 商品信息 -->
      <div class="product" v-show="false">
        <div class="productPic"></div>

        <div class="productInfo">
          <div class="productName">computer monitor</div>
          <div class="productPrice"><span>Pi</span> 96</div>
        </div>

        <div class="right">
          <div class="circle"></div>
          <div class="sendBox">Send</div>
        </div>
      </div>

      <!-- 底部一栏 -->
      <div class="footer" v-if="msgList.list">
        <div class="inp_bar">
          <!-- 输入框 -->
          <div class="boxForInput">
            <input :placeholder="$t('message.enter')" @keydown.enter="input" v-model="msg" type="text" />
            <!-- <div class="plus" @click="input"><img src="/images/上箭头.png"></div> -->
          </div>

          <!-- 加号 -->
          <div class="plus" @click="showPlus = !showPlus">
            <img src="/images/Message/plus.png" alt="" />
          </div>
        </div>

        <!-- 点击加号显示（功能面板） -->
        <div class="functionPanel" v-show="showPlus">
          <div class="item">
            <img src="/images/Message/Album.png" alt="" />
            <span>Album</span>
          </div>
          <div class="item">
            <img src="/images/Message/camera.png" alt="" />
            <span>Photograph</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.loadingView {
  margin-top: 90rem;

  >div {
    margin-bottom: 20rem;
    flex-direction: row-reverse;

    &:nth-of-type(2n) {
      flex-direction: row;
    }
  }
}

.outside {
  max-height: 100vh;
  min-height: 100vh;
  overflow: scroll;

  &::-webkit-scrollbar {
    display: none;
  }

  // 头部一栏
  .header {
    position: sticky;
    z-index: 100;
    top: 0;

    height: 64rem;
    background-color: #f5f5f5;

    display: flex;
    align-items: center;
    justify-content: space-between;

    .back {
      img {
        width: 9rem;
        margin-left: 25rem;
      }
    }

    .personName {
      position: absolute;
      left: 0;
      right: 0;
      margin: auto;

      width: max-content;
      color: #000;
      font-size: 20rem;
    }
  }

  .album {
    position: relative;
    background-color: #f5f5f5;
    border-radius: 12rem;
    margin: 20rem 16rem;
    padding: 12rem;
    display: flex;

    .albumPic {
      width: 94rem;
      height: max-content;

      img {
        width: 100%;
      }
    }

    .albumInfo {
      position: absolute;
      top: 10rem;
      left: 122rem;
      display: inline-block;
      font-size: 14rem;
    }

    .price {
      position: absolute;
      bottom: 12rem;
      right: 12rem;

      display: inline-block;
      color: #642e8e;
      font-size: 16rem;

      span {
        color: #000;
        font-size: 12rem;
      }
    }
  }

  .communication {
    padding: 16rem 16rem 190rem;

    .userAvatar {
      width: 50rem;
      height: 50rem;
      border-radius: 50%;
      overflow: hidden;

      img {
        width: 50rem;
      }
    }

    .item {
      display: flex;
      // 想不到吧！设置反转！
      margin-bottom: 30rem;
      align-items: flex-start;

      .message {
        word-wrap: break-word;
        max-width: 244rem;
        font-size: 16rem;
        line-height: 22rem;
        color: #999;

        margin: 0 12rem;

        background-color: #f5f5f5;
        border-radius: 12rem;
        padding: 10rem 16rem;
      }

      &.sender {
        flex-direction: row-reverse;

        >.message {
          color: #642e8e;
          background-color: #d0c0dd;
        }
      }
    }
  }

  // 商品信息
  .product {
    position: fixed;
    bottom: 90rem;
    align-items: center;

    display: flex;

    width: 358rem;
    height: 80rem;
    background-color: #f5f5f5;
    border-radius: 12rem;
    margin: 0 16rem;

    .productPic {
      width: 60rem;
      height: 60rem;
      border-radius: 4rem;
      background-color: #494c4d;
      margin: 10rem;
    }

    .productInfo {
      height: 100%;
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: space-around;

      .productName {
        color: #333;
        font-size: 16rem;
      }

      .productPrice {
        color: #642e8e;
        font-size: 16rem;

        span {
          color: #000;
          font-size: 12rem;
        }
      }
    }

    .right {
      display: flex;
      width: 75rem;
      height: 100%;

      flex-direction: column;
      justify-content: space-evenly;
      align-items: flex-end;

      .circle {
        width: 16rem;
        height: 16rem;
        background-color: #494c4d;
        border-radius: 50%;
        margin-right: 10rem;
      }

      .sendBox {
        align-self: flex-end;

        width: 75rem;
        height: 30rem;
        border-radius: 40rem;
        background-color: #642e8e;
        margin-right: 10rem;

        color: white;
        font-size: 16rem;
        text-align: center;
        line-height: 30rem;
      }
    }
  }

  // 底部一栏
  .footer {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;

    background-color: #f5f5f5;
    padding: 14rem;

    >.inp_bar {
      display: flex;
      align-items: center;

      .boxForInput {
        flex: 1;

        margin-right: 28rem;

        input {
          background-color: #fff;
          border-radius: 20rem;
          height: 34rem;
          width: 100%;

          padding-left: 15rem;
          font-size: 18rem;
        }
      }

      .plus {
        display: inline-block;
        width: 30rem;
        height: 30rem;
        border-radius: 50%;
        background-color: #fff;

        img {
          width: 13rem;
          height: 28rem;
          margin-left: 9rem;
        }
      }
    }

    // 功能面板
    >.functionPanel {
      display: flex;

      width: 100%;
      height: 199rem;
      background-color: #f5f5f5;

      .item {
        width: 25%;
        height: 90rem;
        // margin: 0 auto;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;

        img {
          width: 40rem;
          height: 40rem;
        }
      }
    }
  }
}
</style>
